<script setup lang="ts">
import { CreateInvoiceAPI } from '@/apis/createInvoice'
import { useUserInfoStore } from '@/store/userInfo'
import { InvoiceTitleType } from '@/types/enum'

const router = useRouter()
const userInfoStore = useUserInfoStore()

const type = ref<'normal' | 'intercity'>()
const ids = ref('')
const money = ref('')

onLoad((options) => {
  if (!options?.type || !options.ids || !options.money) {
    uni.showToast({ title: '获取数据失败', icon: 'none' })
    return
  }
  type.value = options.type
  ids.value = options.ids
  money.value = options.money
})

/* ------------------------------- Form START ------------------------------- */
const formRef = ref<HTMLFormElement | null>(null)

const formData = ref({
  type: InvoiceTitleType.enterprise,
  invoice_title: '',
  ratepay_number: '',
  remark: '',
  email: '',
})

const rules = {
  title: {
    required: true,
    message: '请输入发票抬头',
  },
  id: {
    required: true,
    message: '请输入纳税人识别号',
  },
  remark: {
    required: true,
    message: '请输入备注等信息',
  },
  email: {
    required: true,
    message: '请输入发票接收邮箱',
  },
}
/* -------------------------------- Form END -------------------------------- */

const isShowSuccessDialog = ref(false)

const popupRef = ref<any>(null)

const titleList = ref<any[]>([])

function handleAddInvoiceTitle() {
  router.push('editingTitleForm')
}

function handleEditInvoiceTitle() {
  router.push('editingTitleForm')
}

function handleViewInvoiceDetail() {
  router.push('invoiceDetail')
}

const handleSubmit = useThrottleFn(() => {
  formRef.value?.validate()
    .then(async () => {
      const res = await CreateInvoiceAPI({
        order_type: type.value === 'normal' ? '2' : '1',
        ids: ids.value,
        invoice_title: formData.value.invoice_title,
        ratepay_number: formData.value.ratepay_number,
        money: money.value,
        email: formData.value.email,
        type: formData.value.type.toString(),
      }, userInfoStore.userInfo!.token!)
      if (res.data?.code !== 1)
        return
      isShowSuccessDialog.value = true
    })
    .catch((errors: AnyObject[]) => {
      if (errors.length > 0)
        uni.showToast({ title: errors[0].message, icon: 'none' })
    })
}, 1000)

function handleExit() {
  router.back()
}
</script>

<template>
  <uv-form ref="formRef" :model="formData" :rules="rules" round="30">
    <ListSectionAlt title="发票信息">
      <ListCellAlt label="抬头类型">
        <view class="flex items-center">
          <view class="flex items-center" @tap="formData.type = InvoiceTitleType.enterprise">
            <Checkbox :checked="formData.type === InvoiceTitleType.enterprise" />
            <Spacer width="14" />
            <view class="text-28rpx text-#333333 font-medium">
              企业单位
            </view>
          </view>
          <Spacer width="36" />
          <view class="flex items-center" @tap="formData.type = InvoiceTitleType.individual">
            <Checkbox :checked="formData.type === InvoiceTitleType.individual" />
            <Spacer width="14" />
            <view class="text-28rpx text-#333333 font-medium">
              个人/非企业单位
            </view>
          </view>
        </view>
      </ListCellAlt>
      <Divider width="702" />
      <ListCellAlt label="发票抬头">
        <view class="flex items-center">
          <view class="flex-1">
            <ListInputAlt v-model="formData.invoice_title" type="text" placeholder="请填写发票抬头" />
          </view>
          <image
            class="ml-32rpx h-32rpx w-29rpx flex-shrink-0"
            src="@/static/images/invoice_black_outline.png"
            @tap="popupRef.open()"
          />
        </view>
      </ListCellAlt>
      <Divider width="702" />
      <ListCellAlt label="纳税人识别号">
        <ListInputAlt v-model="formData.ratepay_number" type="text" placeholder="请填写纳税人识别号" />
      </ListCellAlt>
      <Divider width="702" />
      <ListCellAlt label="发票金额" @tap="handleViewInvoiceDetail">
        <view class="flex items-center justify-between">
          <view class="text-28rpx text-#F94A36 font-medium">
            {{ money || '0' }}元
          </view>
          <!-- <view class="text-28rpx text-#999999 font-medium">
            共1张发票，请查看>
          </view> -->
        </view>
      </ListCellAlt>
      <Divider width="702" />
      <ListCellAlt label="更多信息">
        <ListInputAlt v-model="formData.remark" type="text" placeholder="请填写备注等信息（非必填）" />
      </ListCellAlt>
    </ListSectionAlt>
    <ListSectionAlt title="接收信息">
      <ListCellAlt label="电子邮箱">
        <ListInputAlt v-model="formData.email" type="text" placeholder="请填写发票接收邮箱" />
      </ListCellAlt>
    </ListSectionAlt>
  </uv-form>
  <RGButton class="fixed bottom-40rpx x-center" size="large" corner="large" @tap="handleSubmit">
    提交
  </RGButton>

  <uv-popup ref="popupRef" mode="bottom">
    <view class="h-720rpx bg-#F8F8F8">
      <view class="relative h-112rpx w-full">
        <view class="absolute left-1/2 top-1/2 text-32rpx text-#333333 font-bold leading-32rpx -translate-1/2">
          选择抬头
        </view>
        <image
          class="absolute right-24rpx top-1/2 h-30rpx w-30rpx -translate-y-1/2"
          src="@/static/images/xmark_black_outline.png"
          @tap="popupRef.close()"
        />
      </view>
      <view class="h-608rpx w-full">
        <EmptyBoundary :is-empty="titleList.length === 0">
          <view class="h-full w-full overflow-y-scroll px-24rpx pb-200rpx pt-30rpx">
            <InvoiceTitle v-for="i in titleList" id="123123123123" :key="i" :title-type="InvoiceTitleType.enterprise" title="123123123" @edit="handleEditInvoiceTitle" />
          </view>
          <template #fallback>
            <view class="h-full flex flex-col items-center justify-center pb-200rpx">
              <image
                class="h-276rpx w-472rpx"
                src="@/static/images/default.png"
              />
              <Spacer height="16" />
              <view class="text-28rpx text-#999999 leading-28rpx">
                暂未添加发票抬头
              </view>
            </view>
          </template>
        </EmptyBoundary>
      </view>
      <view class="absolute bottom-40rpx x-center">
        <RGButton @tap="handleAddInvoiceTitle">
          添加常用发票抬头
        </RGButton>
      </view>
    </view>
  </uv-popup>

  <uv-overlay :show="isShowSuccessDialog" @tap="isShowSuccessDialog = false">
    <uv-transition mode="zoom-in" :show="isShowSuccessDialog">
      <view class="relative h-screen w-screen">
        <view class="absolute left-50% top-50% -translate-50%">
          <Dialog
            :show-cancel-button="false"
            title="提交成功"
            content="您的发票信息已经提交，请耐心等待开票，发票将会下发至您的邮箱，请及时查收..."
            confirm-label="确定"
            @cancel="isShowSuccessDialog = false"
            @confirm="handleExit"
          >
            <template #icon>
              <image
                class="h-164rpx w-167rpx"
                src="@/static/images/checkmark_colorful.png"
              />
            </template>
          </Dialog>
        </view>
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'invoiceForm'
style:
  navigationBarTitleText: '开具电子发票'
</route>
